package com.example.adminserivce.Controller;

import com.example.adminserivce.Service.ActivityService;
import com.example.adminserivce.Service.UserService;
import com.example.adminserivce.domain.Vo.ActivityStatistics;
import com.example.common.constants.RdsConstants;
import com.example.common.constants.RoleConstants;
import com.example.common.domain.Result;
import com.example.common.domain.pojo.Activity;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RefreshScope // 实时刷新配置信息
@Slf4j  // 日志 log.info("登录日志测试：");
@RequiredArgsConstructor
@RestController
@RequestMapping("/admins/statistics")
@Api(value = "管理员活跃度统计", description = "活跃度统计")
public class ActivityStatisticsController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService; // 用于获取总用户数的服务
    @Autowired
    private ActivityService activityService;

    /**
     * 查询教师活跃度统计（日）不传默认当天的
     * @param date
     * @return
     */
    @GetMapping("/teacher/activity")
    public Result<ActivityStatistics> getTeacherActivity(
            @RequestParam(required = false) String date
    ) {
        if (date == null) {
            date = LocalDate.now().toString();
        }
        // 获取活跃教师数
//        Long activeCount = redisTemplate.opsForHyperLogLog().size("teacher:active:" + date);
        Long activeCount = redisTemplate.opsForHyperLogLog().size(RdsConstants.TEACHER_ACTIVE + date);
        // 获取教师总数（从数据库或其他服务获取）
        Long totalCount = userService.getTotalTeacherCount();
        // 计算活跃百分比
        Double percentage = activityService.calculatePercentage(activeCount, totalCount);
        // 模块访问分布
        Map<String, Long> moduleDistribution = activityService.getModuleDistribution(RoleConstants.TEACHER, date);
        // 构建统计结果
        ActivityStatistics statistics = new ActivityStatistics(
                activeCount,
                totalCount,
                percentage,
                moduleDistribution
        );
        return Result.success(statistics);
    }

    /**
     * 查询学生活跃度统计(日)不传默认当天
     *
     * @param date
     * @return
     */
    @GetMapping("/student/activity")
    public Result<ActivityStatistics> getStudentActivity(
            @RequestParam(required = false) String date
    ) {
        if (date == null) {
            date = LocalDate.now().toString();
        }
        // 获取活跃学生数
        Long activeCount = redisTemplate.opsForHyperLogLog().size(RdsConstants.STUDENT_ACTIVE + date);
        // 获取学生总数
        Long totalCount = userService.getTotalStudentCount();
        // 计算活跃百分比
        Double percentage = activityService.calculatePercentage(activeCount, totalCount);
        // 模块访问分布
        Map<String, Long> moduleDistribution = activityService.getModuleDistribution(RoleConstants.STUDENT, date);
        // 构建统计结果
        ActivityStatistics statistics = new ActivityStatistics(
                activeCount,
                totalCount,
                percentage,
                moduleDistribution
        );
        return Result.success(statistics);
    }

    /**
     * 查询教师周活跃度（不传日期时默认当前周）
     *
     * @param date
     * @return
     */
    @GetMapping("/teacher/activity/week")
    public Result<ActivityStatistics> getTeacherWeeklyActivity(
            @RequestParam(required = false) LocalDate date
    ) {
        ActivityStatistics statistics = activityService.getWeeklyActivity(RoleConstants.TEACHER, date);
        return Result.success(statistics);
    }

    /**
     * 查询学生周活跃度（不传日期时默认当前周）
     *
     * @param date
     * @return
     */
    @GetMapping("/student/activity/week")
    public Result<ActivityStatistics> getStudentWeeklyActivity(
            @RequestParam(required = false) LocalDate date
    ) {
        ActivityStatistics statistics = activityService.getWeeklyActivity(RoleConstants.STUDENT, date);
        return Result.success(statistics);
    }

    /**
     * 查询教师某段时间内的日活跃度（天为单位，开始日期不能超过规定日期2025.5.20）
     *
     * @param startDate 开始日期（格式：YYYY-MM-DD）
     * @param endDate   结束日期（格式：YYYY-MM-DD）
     * @return 日活跃度列表
     */
    @GetMapping("/teacher/activity/day-range")
    public Result<List<Activity>> getTeacherDailyActivityByRange(
            @RequestParam("startDate") LocalDate startDate,
            @RequestParam("endDate") LocalDate endDate
    ) {
        List<Activity> entities = activityService.getDailyActivityByDateRange(
                RoleConstants.TEACHER, startDate, endDate
        );
        return Result.success(entities);
    }

    /**
     * 查询学生某段时间内的日活跃度（天为单位，开始日期不能超过规定日期2025.5.20）
     *
     * @param startDate 开始日期（格式：YYYY-MM-DD）
     * @param endDate   结束日期（格式：YYYY-MM-DD）
     * @return 日活跃度列表
     */
    @GetMapping("/student/activity/day-range")
    public Result<List<Activity>> getStudentDailyActivityByRange(
            @RequestParam("startDate") LocalDate startDate,
            @RequestParam("endDate") LocalDate endDate
    ) {
        List<Activity> entities = activityService.getDailyActivityByDateRange(
                RoleConstants.STUDENT, startDate, endDate
        );
        return Result.success(entities);
    }


}